package mr.fresh.entity.tool;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.UUID;

/**
 * @CLassName Noutli
 * @Description TODO
 * @Author mr.jl
 * @Date 2019/6/7 17:38
 * @Version 1.0
 **/
public class NoUtli {
    /**
     * 商品编号号生成计数器
     */
    private static long numberCount = 0L;
    /**
     * 每毫秒生成商品编号数量最大峰值
     */
    private static final int maxPerMSECSize = 20000;

    /**
     * @Description: 生成编号工具
     * @Param: []
     * @return: java.lang.String
     * @Author: Mr.jl
     * @Date: 2019/6/7
     */
    public static String makeNo() {
        ReferenceQueue<StringBuilder> queue = new ReferenceQueue<StringBuilder>();
        WeakReference<StringBuilder> weakRef = new WeakReference<StringBuilder>(new StringBuilder(15), queue);
        synchronized (weakRef) {
            if (null == weakRef.get()) {
                weakRef = new WeakReference<StringBuilder>(new StringBuilder(15), queue);
            }
            // 计数器到最大值归零,目前1毫秒处理峰值1个
            if (numberCount >= maxPerMSECSize) {
                numberCount = 0L;
            }
            // HASH-CODE
            weakRef.get().append(Math.abs(UUID.randomUUID().toString().hashCode()));
            // 计数器的值
            weakRef.get().append(numberCount++);
            return weakRef.get().toString();
        }
    }
}
